package com.app.lcl.test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.app.lcl.entities.Laboratory;
import com.app.lcl.entities.Student;

public class testJunit3 {
	
	private SessionFactory sf = null;
	private Session session = null;
	private Transaction tx = null;
	/**
	 * 测试前
	 * @throws Exception
	 */
	@Before
	public void setUp() throws Exception{
		System.out.println("----初始化数据----");
		Configuration conf = new Configuration().configure();
		StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder().applySettings(conf.getProperties());
		StandardServiceRegistry sr = srb.build();
		sf = conf.buildSessionFactory(sr);
		session = sf.openSession();
	}
	/**
	 * 测试后
	 * @throws Exception
	 */
	@After
	public void tearDown() throws Exception{
		System.out.println("----释放数据----");
		if(session.isOpen()){
			session.close();
		}
	}
	
	@Test
	public void testSaveLab(){
		Laboratory lab = new Laboratory(4212, "boss");
		Student student1 = new Student("151307040017", "李成龙", 24);
		Student student2 = new Student("151307040010", "周思琪", 22);
		Student student3 = new Student("161307040007", "吴丹丹", 23);
		Student student4 = new Student("161307040005", "季琳雅", 21);
		Set<Student> studentSet = new HashSet<Student>();
		studentSet.add(student1);
		studentSet.add(student2);
		studentSet.add(student3);
		studentSet.add(student4);
		lab.setStudentSet(studentSet);
		student1.setLab(lab);
		student2.setLab(lab);
		student3.setLab(lab);
		student4.setLab(lab);
		
		tx = session.beginTransaction();
		session.persist(lab);
		//session.persist(student1);
		tx.commit();
	}
	@Test
	/**
	 * 根据主表获取从表数据
	 */
	public void GetA(){
		Laboratory lab = (Laboratory) session.get(Laboratory.class, 4212);
		System.out.println(lab);
		System.out.println("-----------------------");
		Iterator<Student> it =	lab.getStudentSet().iterator();
		while(it.hasNext()){
			Student student = it.next();
			System.out.println(student);
		}
	}
	
	@Test
	/**
	 * 根据从表获取主表数据
	 */
	public void GetB(){
		Student student = (Student) session.get(Student.class, "151307040017");
		System.out.println(student);
		System.out.println("-------------------------");
		System.out.println(student.getLab());
	}
}
